package com.ruge.core.config;

import com.ruge.tool.str.StringTool;
import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;

import java.util.Locale;

/**
 * description:
 * create time at 2022/6/6 12:02
 *
 * @author alice.ruge
 * @since 0.0.3
 */

public class MyPhysicalNamingStrategy extends PhysicalNamingStrategyStandardImpl {

    /**
     * 数据库表前缀
     */
    private String prefix;

    /**
     * 数据库表后缀
     */
    private String suffix;

    /**
     * 重写方法实现自动追加前缀后缀
     */
    @Override
    public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment context) {
        StringBuilder sb = new StringBuilder();
        if (StringTool.isNotBlank(prefix)) {
            sb.append(prefix);
        }
        sb.append(name.getText());
        if (StringTool.isNotBlank(suffix)) {
            sb.append(suffix);
        }
        String underscores = addUnderscores(sb.toString());
        return new Identifier(underscores, name.isQuoted());
    }

    @Override
    public Identifier toPhysicalColumnName(Identifier name, JdbcEnvironment context) {
        return super.toPhysicalColumnName(name, context);
    }

    protected static String addUnderscores(String name) {
        StringBuilder buf = new StringBuilder(name.replace('.', '_'));
        for (int i = 1; i < buf.length() - 1; i++) {
            if (
                    Character.isLowerCase(buf.charAt(i - 1)) &&
                            Character.isUpperCase(buf.charAt(i)) &&
                            Character.isLowerCase(buf.charAt(i + 1))
            ) {
                buf.insert(i++, '_');
            }
        }
        return buf.toString().toLowerCase(Locale.ROOT);
    }
}
